<?php

namespace app\admin\controller\service\shop;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 商家管理
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\service\shop\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\shop\Shop;
        $this->view->assign("toShopList", $this->model->getToShopList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("stateList", $this->model->getStateList());
    }


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $startTime = strtotime(date("Y-m-d",time()));
        foreach ($list as &$row)
        {
            $row->categoryname = $row->category_ids?model('app\admin\model\service\Category')->getCategoryList($row->category_ids):'';
            $row->goodsname = $row->goods_ids?model('app\admin\model\service\Goods')->getGoodsList($row->goods_ids):'';
            $row->shopmoney = \app\admin\model\service\User::where('user_id',$row->user_id)->value('shop_user_money');
            $row->already_accept_nums = \app\admin\model\service\order\Order::where(['shop_id'=>$row->id,'status'=>['>',1],'starttime'=>['>=',$startTime]])->count();
            $row->update_time = $row->updatetime?date("Y-m-d",$row->updatetime):'';
            $row->create_time = date("Y-m-d",$row->createtime);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row->city = $row->province.'/'.$row->city.'/'.$row->district;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['district'] = isset($address[2])?:'';
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function deduct($ids = null)
    {
        $row = $this->model->get($ids);
        if($this->request->isPost())
        {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try{
                $params['shop_ensure']>$row->ensure_price && $this->error('保证金不足,无法扣除');
                \app\api\model\service\Shop::money(-$params['skill_ensure'], $row->user_id, $params['skill_note']);
                Db::commit();
                $this->success('保证金已扣除');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保证金扣除失败',$e->getMessage());
            }
        }
        $this->assign(['row'=>$row]);
        return $this->view->fetch();
    }


}
